package com.ruoyi.core.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.core.domain.ClientProductUser;
import com.ruoyi.core.manager.ProductUserCookieResourceManager;
import com.ruoyi.core.mapper.ClientProductUserMapper;
import com.ruoyi.common.utils.JacksonUtil;
import com.ruoyi.core.mapper.ServerConfigMapper;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import io.jsonwebtoken.lang.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: Junglescou 应用cookie 刷新任务
 * @Company: 北京卡拉卡尔股份技术有限公司
 * @Author: Darren Ho
 * @Date: 10/27/2020 18:44
 */
@Component
public class JungleScoutCookieRefreshJob implements InitializingBean, CookieRefreshTPeriodicTriggerJob {

    private final Logger logger = LoggerFactory.getLogger(JungleScoutCookieRefreshJob.class);

    private Integer cookieRefreshTimeInterval;

    @Autowired
    private ClientProductUserMapper clientProductUserMapper;

    @Autowired
    private ProductUserCookieResourceManager productUserCookieResourceManager;

    @Autowired
    private ISysConfigService sysConfigService;

    private RestTemplate restTemplate;

//    @Value("${jungle-scout.login.url:http://8.210.233.182:3000/login?id=%s&userName=%s&password=%s&type=1} ")
//    private String requestUrl;

    private Integer retryTime = 1;

    @Autowired
    private ServerConfigMapper serverConfigMapper;

    @Override
    public void afterPropertiesSet() throws Exception {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(2 * 60 * 1000);
        simpleClientHttpRequestFactory.setReadTimeout(2 * 60 * 1000);
        restTemplate = new RestTemplate(simpleClientHttpRequestFactory);
        //

        int jungleScoutCookieRefreshTimeIntervalInter = 60;

        String jungleScoutCookieRefreshTimeInterval = sysConfigService.selectConfigByKey("JUNGLE_SCOUT_COOKIE_REFRESH_TIME_INTERVAL");

        if (!StringUtils.hasText(jungleScoutCookieRefreshTimeInterval)) {
            SysConfig sysConfig = new SysConfig();
            sysConfig.setConfigKey("JUNGLE_SCOUT_COOKIE_REFRESH_TIME_INTERVAL");
            sysConfig.setConfigValue(String.valueOf(jungleScoutCookieRefreshTimeIntervalInter));
            sysConfig.setConfigName("JUNGLE_SCOUT_COOKIE 刷新开关定时更新时间配置项");
            sysConfig.setCreateBy("admin");
            sysConfig.setConfigType("Y");
            sysConfigService.insertConfig(sysConfig);
        } else {
            jungleScoutCookieRefreshTimeIntervalInter = Integer.parseInt(jungleScoutCookieRefreshTimeInterval);
        }
        setCookieRefreshTimeInterval(jungleScoutCookieRefreshTimeIntervalInter);
    }

    @Override
    public void start(List<ClientProductUser> clientProductUsers) {
        if ((clientProductUsers != null && !clientProductUsers.isEmpty())) {
            String requestUrl = serverConfigMapper.selectAvailableNode().getIp();
            if(requestUrl == null){
                logger.error("配置缺失,检查配置");
                return;
            }
            clientProductUsers.forEach(item -> {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                logger.info("jungle scout product user  refresh begin {} ", simpleDateFormat.format(new Date()));
                for (int i = 1; i <= retryTime; i++) {
                    boolean result = refreshCookie(item,requestUrl);
                    logger.info("Jungle scout 登录第{}次执行结果为{}", i, result);
                    if (result) {
                        break;
                    }
                }
            });
        }
    }

    @Override
    public Integer getCookieRefreshTimeInterval() {
        return this.cookieRefreshTimeInterval;
    }

    @Override
    public void setCookieRefreshTimeInterval(Integer cookieRefreshTimeInterval) {
        this.cookieRefreshTimeInterval = cookieRefreshTimeInterval;
        logger.info("update jungle scout  cookie refresh time interval :[{}]", cookieRefreshTimeInterval);
    }

    private Boolean refreshCookie(ClientProductUser clientProductUser,String requestUrl) {

        try {
            Assert.notNull(clientProductUser, " client product user must not be null");
            requestUrl = requestUrl + "login?id=%s&userName=%s&password=%s&type=1";
            String url = String.format(requestUrl, clientProductUser.getId(), clientProductUser.getUsername(), clientProductUser.getPassword());
            logger.info("Jungle Refresh Cookie RequestUrl:{}",requestUrl);
            ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
            logger.info("刷新jungle cookie request url:{}",requestUrl);
            int value = entity.getStatusCode().value();
            logger.info("jungle scout  应用登录响应状态[{}]", value);
            if (!(value >= 200 && value < 300)) {
                return false;
            }

            logger.info("jungle scout  登录响应[{}]", entity.getBody());
            CookieRefreshedResult body = JacksonUtil.fromJson(entity.getBody(), CookieRefreshedResult.class);
            if (body.getCode() != 200) {
                logger.info("jungle scout  应用登录失败，失败原因[{}]", body.getCookie());
                return false;
            }

            ClientProductUser productUser = new ClientProductUser();
            productUser.setId(body.getId());
            productUser.setCookie(body.getCookie());
            productUser.setUpdateTime(DateUtils.getNowDate());
            productUser.setAvailable(1);
            clientProductUserMapper.update(productUser);

            // 更新缓存cookie
            productUserCookieResourceManager.setCookie(productUser.getId(), productUser.getCookie());
        } catch (Exception e) {
            logger.info("jungle scout 登录失败,失败原因【{}】", e.getLocalizedMessage());
            return false;
        }

        return true;
    }

}

